<template>
    <!-- 课程资料管理 -->
    <!-- 杨珅 2023年6月26日14:06:49 -->
    <div>
        <el-card>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-s-home" style="font-weight:bold"></i> 后台管理</el-breadcrumb-item>
                <el-breadcrumb-item><a href="/">课程资料管理</a></el-breadcrumb-item>
                <el-breadcrumb-item></el-breadcrumb-item>
            </el-breadcrumb>
        </el-card>
        <el-card style="margin-top:20px">
            <div style="background-color:white;">
                <el-button type="primary" @click="openadd()" style="margin-left:1050px;" size="small">新增</el-button>
                <!-- 全查 -->
                <el-table :data="CourseFileData" style="width: 100%; margin-top: 10px; margin-left: 15px;"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="imageId" label="课程封面">
                        <template slot-scope="scope">
                            <el-image style="width: 112px; height: 70px"
                                :src="'http://101.43.223.224:8765/image/getImageById?id=' + scope.row.imageId"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="courseTitle" label="课程标题">
                    </el-table-column>
                    <el-table-column prop="jointIntroduction" label="章节">
                    </el-table-column>
                    <el-table-column prop="fileName" label="资料名称">
                    </el-table-column>
                    <el-table-column prop="information" label="资料介绍">
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="300">
                        <template slot-scope="scope">
                            <el-button @click="yulan(scope.row)"
                            type="primary" size="small">预览</el-button>
                            <el-button @click="openupdate(scope.row)"
                            type="primary"  size="small">修改</el-button>
                            <el-button @click="deleteCourseFileById(scope.row.id)"
                           type="primary" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-pagination :page-sizes="[7, 20, 30, 40]" :page-size="pages.pageSize" background
                    layout="total, sizes, prev, pager, next, jumper" :total="pages.total" :current-page.sync="pages.pageNum"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top:20px"></el-pagination>
            </div>
            <!-- 添加修改弹窗 -->
            <el-dialog :visible.sync="updateadd" width="39%" :before-close="handleClose()" style="text-align:left">
                <div slot="title" class="header-title" style="text-align:left;font-weight: bold;color:white;font-size:18px;margin-bottom: 10px;">
                    新增/编辑课程资料
                </div> 
                <el-form stripe style="width: 100%" :model="addfrom">
                    <el-form-item prop="jointId" width="200">
                        <span style="font-weight:900;color:rgb(93,142,255)">|</span>
                        <span style="margin-left:20px">章节名称</span>
                        <el-select v-model="addfrom.jointId" placeholder="请选择课程名称" style="margin-left:20px">
                            <el-option :label="item.jointIntroduction" :value="item.id" v-for="item in selectData" :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item prop="file" width="200">
                        <span style="font-weight:900;color:rgb(93,142,255)">|</span>
                        <span style="margin-left:20px">上传资料</span>
                        <!-- 上传文件 -->
                        <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/"
                            :on-preview="handlePreview" :on-emover="handleRemove" :before-remove="beforeRemove"
                            :before-upload="beforeAvatarUpload" multiple :limit="3" :on-exceed="handleExceed"
                            style="margin-top:-40px;margin-left:100px">
                            <el-button size="small" type="primary">点击上传(仅支持pdf)</el-button>
                        </el-upload>
                    </el-form-item>

                    <el-form-item prop="information" width="300px">
                        <span style="font-weight:900;color:rgb(93,142,255)">|</span>
                        <span style="margin-left:20px">资料介绍</span>
                        <el-input style="width:500px;margin-left:20px" v-model="addfrom.information"></el-input>
                    </el-form-item>

                </el-form>
                <div style="text-align:center">
                    <el-button style="background-color:rgb(234,244,255);color:rgb(96,169,255)" @click="addCourseFile()">确定</el-button>
                    <el-button @click="updateadd = false" style="background-color:rgb(234,244,255);color:rgb(96,169,255)">取消</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>
<script>
export default {
    name: "yonghu",
    data() {
        return {
            // 存放文件
            File: File,
            selectData: [], //下拉数据
            ids: [],//批量删除id
            //全查
            CourseFileData: [],
            //分页
            pages: {
                total: 0, //数据总条数
                pageNum: 1, //当前页
                pageSize: 6, //每页几条数据
            },
            //添加/编辑表单
            addfrom: {
                id: "",
                jointId: "",
                information: "",
            },
            //添加修改弹窗
            updateadd: false,
        };
    },
    mounted() {
        this.getCourseFile()

    },
    methods: {
        yulan(data) {
            window.open(this.$openFile + '/image/getFileById?id=' + JSON.parse(JSON.stringify(data)).fileId)
        },
        //全查-模糊查
        getCourseFile() {
            this.$axios
                .get("/coursefile/getCourseFile", {
                    params: {
                        pageNum: this.pages.pageNum, //当前页
                        pageSize: this.pages.pageSize, //每页几条数据
                    }
                })
                .then((res) => {
                    if (res.data.code) {
                        this.CourseFileData = res.data.data.content;
                        this.pages.total = res.data.data.totalSize;
                    }
                })
                .catch((err) => {
                    this.myMessage("error", err);
                });
        },
        //打开添加弹窗
        openadd() {
            this.addfrom = {}//清空表单数据
            this.selectAuthority()//初始化下拉数据
            this.updateadd = true;
        },
        //打开编辑弹窗
        openupdate(data) {
            this.addfrom = JSON.parse(JSON.stringify(data)); //回显
            this.selectAuthority()//初始化下拉数据
            this.updateadd = true;
        },
        //动态下拉数据
        selectAuthority() {
            this.$axios
                .get("/coursefile/fileSelect", {
                })
                .then((res) => {
                    if (res.data.code) {
                        this.selectData = res.data.data;
                    }
                })
                .catch((err) => {
                    this.myMessage("error", err);
                });
        },
        //添加/编辑
        addCourseFile() {
            if (!this.addfrom.id) {
                const formdata = new FormData()
                formdata.set('file', this.File, this.File.name)
                formdata.set('jointId', this.addfrom.jointId)
                formdata.set('information', this.addfrom.information)
                this.$axios
                    .post("/coursefile/addCourseFile", formdata)
                    .then((res) => {
                        if (res.data.code) {
                            this.myMessage("success", "添加成功");
                            this.getCourseFile()//跳转全查页面
                            this.updateadd = false
                        }
                    })
                    .catch((err) => {
                        this.myMessage("error", err);
                    });
            } else {
                //修改信息
                this.$axios
                    .put("/coursefile/updateCourseFile", this.addfrom)
                    .then((res) => {
                        if (res.data.code) {
                            this.myMessage("success", "修改成功");
                            this.getCourseFile()//跳转全查页面
                            this.updateadd = false
                        } else {
                            this.myMessage("warning", "修改失败！");
                        }
                    });
            }
        },
        // 添加文件规则
        beforeAvatarUpload(file) {
            console.log(file)
            const isPDF = file.type === 'application/pdf'
            const isDOCX = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            const isLt2M = file.size / 1024 / 1024 < 10
            if (!isPDF && !isDOCX) {
                this.$message.error('上传头像图片只能是 JPG 格式!')
                return false
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 5MB!')
                return false
            }
            this.File = file
            this.imageUrl = URL.createObjectURL(file)
            return false
        },
        //选择数据数量
        handleSelectionChange(val) {
            this.ids = val.map(v => v.id)
            // this.$message.warning("选择了"+this.ids.length+"条数据");
        },
        //逻辑删除
        deleteCourseFileById(id) {
            this.$confirm('此操作将价格彻底删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.delete('/coursefile/deleteCourseFileById', {
                    params: {
                        id: id
                    }
                }).then(res => {
                    if (res.data.code == 200) {
                        this.myMessage('success', '删除成功')
                        this.getCourseFile()
                    } else {
                        this.myMessage('warning', '删除失败')
                    }
                }).catch(res => {
                    this.myMessage('error', '删除失败，请联系管理员')
                })
            }).catch(res => {
                this.myMessage('info', '已取消删除')
            })
        },
        myMessage(type, message) {
            this.$message({
                message: message,
                type: type
            })
        },

        //分页
        handleSizeChange(val) {
            this.pages.pageSize = val;
            this.getCourseFile();
        },
        handleCurrentChange(val) {
            this.pages.pageNum = val;
            this.getCourseFile();
        },
        //信息
        myMessage(type, message) {
            this.$message({
                message: message,
                type: type,
            });
        },
        handleOpen(key, keyPath) {
            console.log(key, keyPath);
        },
        handleClose(key, keyPath) {
            console.log(key, keyPath);
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            window.open(this.$openFile + '/image/getFileById?id=1')
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        }
    },
};
</script>
<style>
/*上传文件按钮*/
.uploader_input {
    width: 120px;

}

.uploader-file-input {
    display: none;
}

/*上传文件展示位置*/
.uploader_file_box {
    display: flex;
}

.uploader__file-list__item {
    padding: 0 1rem;
    display: flex;
    background-color: #dfdfdf;
    margin-right: 10px;
}

.btn-white-up {
    background-color: #fff;
    border: 1px dashed #cccccc;
}

.uploader__file-list__text {
    max-width: 100px;
    padding-right: 10px;
    display: inline-block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.uploader__file-list__text:hover {
    color: #478aee;
}

.js-upload-remove-button {
    cursor: pointer;
}
.el-dialog__header {
  background: rgb(93,142,255);
  text-align: center;
}


</style>